#coding=utf-8

import time,mmap
import numpy
from threading import Thread
import fcntl
import posix_ipc
import cv2
import signal
import os

sempty = None
sfull = None
is_exit = False

share_path = "/tmp/test_1"

def sigint_handler(signum, frame):
    global sempty
    global sfull
    global is_exit
    global IsExit
    if is_exit == True:
        exit(-1)
        return
    is_exit = True
    if sempty != None:
        sempty.close()
    if sfull != None:
        sfull.close()

    print('catched interrupt signal!')
    time.sleep(1)
    exit(-1)

signal.signal(signal.SIGINT, sigint_handler)
signal.signal(signal.SIGHUP, sigint_handler)
signal.signal(signal.SIGTERM, sigint_handler)
        
def pic_receive_thread():
    prefix = share_path
    prefix = "/" + prefix.replace("/", ".")
    empty_key = prefix + ".empty"
    full_key = prefix + ".full"
    sempty = posix_ipc.Semaphore(empty_key, posix_ipc.O_CREAT, initial_value=1)
    sfull = posix_ipc.Semaphore(full_key, posix_ipc.O_CREAT, initial_value=0)
    global is_exit
    try:
        with open(share_path, "r+b") as f:
            mm = mmap.mmap(f.fileno(), 0)
            while is_exit != True:
                try:
                    res = sfull.acquire(1)
                except Exception as e:
                    print('acquire full error.' + str(e))
                    continue
                fcntl.flock(f, fcntl.LOCK_EX)
                mm.seek(0)  
                print(mm.read(16))
                fcntl.flock(f, fcntl.LOCK_UN)
                sempty.release()
    except Exception as e:
        print(str(e))
    print('pic recevie quit')    
    sempty.close()
    sfull.close()
    sempty = None
    sfull = None


receive_thread = Thread(target=pic_receive_thread)
receive_thread.start()
receive_thread.join()

print('quit')
